<?php

/*
 * 上传图像模型
 * @author turtle
 * create_time 2017-01-04
 */

namespace App\Admin\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Intervention\Image\Constraint;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class UploadImg extends Model {

    /*
     * 上传图像
     * @author sky
     * create_time 2017-03-26
     */
protected $table = 'mini_goods';

    public static function upload($image, $slug) {
        $fullFilename = null;
        $resizeWidth = 1800;
        $resizeHeight = null;
        $file = $image;
        $filename = 'avatar'.Str::random(10);
        $fullPath = $slug.'/'.$filename.'.'.$file->getClientOriginalExtension();

        $ext = $file->guessClientExtension();

        if (in_array($ext, ['jpeg', 'jpg', 'png', 'gif'])) {
            $image = Image::make($file)
                ->resize($resizeWidth, $resizeHeight, function (Constraint $constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                })  
                ->encode($file->getClientOriginalExtension(), 75);
            if (Storage::put('public/'.$fullPath, (string) $image, 'public')) {
                $status = '图像上传成功!';
                $fullFilename = $fullPath;
            } else {
                $status = '上传图像失败：未知错误！';
            }   
        } else {
            $status = '上传图像失败: 不支持的图像格式或图像太大!';
        }
        return $fullFilename;
    }
     /*
     * 添加商品
     * @author sky
     * create_time 2017-03-26
     */
    public static function addGoods($arr){
        UploadImg::insert($arr);
    }

}
